﻿using System;
using System.IO;

namespace DevelopTool.Common
{
    /// <summary>
    /// 目录帮助类
    /// </summary>
    public class DirectoryHelper
    {
        /// <summary>
        /// 尝试删除非空目录
        /// </summary>
        /// <param name="dir">目录</param>
        /// <returns>结果</returns>
        public static bool TryDelete(string dir)
        {
            try
            {
                Directory.Delete(dir);
                return !Directory.Exists(dir);
            }
            catch (Exception)
            {
                return false;
            }
        }


        /// <summary>
        /// 清空指定的目录，但不删除目录
        /// </summary>
        /// <param name="dir">目录</param>
        public static void EmptyDir(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                if (File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly", StringComparison.Ordinal) != -1)
                    {
                        fi.Attributes = FileAttributes.Normal;
                    }

                    fi.TryDelete();
                }
                else
                {
                    DirectoryInfo d1 = new DirectoryInfo(d);
                    EmptyDir(d1.FullName); //递归删除子目录
                    TryDelete(d);
                }
            }
        }

        /// <summary>
        /// 删除指定的目录
        /// </summary>
        /// <param name="dir">目录</param>
        public static void DeleteDir(string dir)
        {
            EmptyDir(dir);
            TryDelete(dir);
        }

        /// <summary>
        /// 在磁盘上创建一个唯一命名的临时目录，并返回该目录的完整路径
        /// </summary>
        public static string GetTempDirName()
        {
            string tempDirectoryPath = Path.Combine(GlobalData.AppTempDirectory,"tempFiles", DateTime.Now.ToString("yyyyMMddHHmmss"));//临时目录

            // 创建临时目录
            if (!Directory.Exists(tempDirectoryPath))
            {
                Directory.CreateDirectory(tempDirectoryPath);
            }
            return tempDirectoryPath;
        }

    }
}
